import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class BaseTextFieldTest extends StatelessWidget {
  final TextEditingController _controller = TextEditingController();

  void initState() {
    // 监听输入改变
    _controller.addListener(() {
      print("listener: ${_controller.text}");
    });
    // 设置默认值不生效呢？
    _controller.text = "sbjun";
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text("1. 初体验。动画，交互都做的很棒呀，👍"),
          Text("仅看效果就好"),
          TextField(
            autofocus: true,
            decoration: InputDecoration(
                labelText: "用户名",
                hintText: "用户名或邮箱",
                prefixIcon: Icon(Icons.person)),
          ),
          TextField(
            decoration: InputDecoration(
                labelText: "密码",
                hintText: "您的登录密码",
                prefixIcon: Icon(Icons.lock)),
            obscureText: true,
          ),
          SizedBox(height: 30),
          Text("2. 重要属性"),
          TextField(),
          Text("只会弹出数字键盘, 可惜chrome中验证不到？:"),
          TextField(keyboardType: TextInputType.number),
          Text("长度限制"),
          TextField(
            maxLength: 5,
            maxLengthEnforcement:
                MaxLengthEnforcement.truncateAfterCompositionEnds,
          ),
          SizedBox(height: 30),
          Text("3.1 获取输入框内容"),
          Text(
              "a. 受控组件，设置state，然后onChange中setState; 得把当前组件BaseTextFieldTest抽成stateful"),
          Text("组件的值怎么传递给外部使用呢？和react一样？", style: TextStyle(color: Colors.red)),
          TextState(),
          Text("b. 绑定controller, 类似于React.createRef()"),
          Text("3.2 监听内容变化"),
          Text("a. 自然得有onChange的"),
          Text("b. 在initState中绑定controller.addListener"),
          TextField(
            decoration:
                InputDecoration(labelText: "添加动态事件, onchange & controller: "),
            onChanged: (value) {
              print("onChanged value: $value");
              print("controller: ${_controller.text}");
            },
            controller: _controller,
          ),
          SizedBox(height: 30),
          Text("4. 焦点相关"),
          FocusTest(),
        ],
      ),
    );
  }
}

class FocusTest extends StatefulWidget {
  @override
  State createState() => _FocusTestState();
}

class _FocusTestState extends State<FocusTest> {
  FocusNode focusNode1 = FocusNode();
  FocusNode focusNode2 = FocusNode();
  FocusScopeNode? focusScopeNode;

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(16.0),
      child: Column(
        children: <Widget>[
          TextField(
            autofocus: true,
            focusNode: focusNode1, //关联focusNode1
            decoration: InputDecoration(labelText: "input1"),
          ),
          TextField(
            focusNode: focusNode2, //关联focusNode2
            decoration: InputDecoration(labelText: "input2"),
          ),
          Builder(
            builder: (ctx) {
              return Column(
                children: <Widget>[
                  ElevatedButton(
                    child: Text("移动焦点到input2"),
                    onPressed: () {
                      //将焦点从第一个TextField移到第二个TextField
                      FocusScope.of(context).requestFocus(focusNode2);
                    },
                  ),
                  ElevatedButton(
                    child: Text("失去焦点，也就是隐藏键盘了"),
                    onPressed: () {
                      // 当所有编辑框都失去焦点时键盘就会收起
                      focusNode1.unfocus();
                      focusNode2.unfocus();
                    },
                  ),
                ],
              );
            },
          ),
        ],
      ),
    );
  }
}

void main(List<String> args) {
  runApp(MaterialApp(
    home: Scaffold(body: BaseTextFieldTest()),
  ));
}

class TextState extends StatefulWidget {
  const TextState({super.key});

  @override
  State<TextState> createState() => _TextState();
}

class _TextState extends State<TextState> {
  String inputStr = "";
  @override
  Widget build(BuildContext context) {
    print("inputStr: $inputStr");
    // return TextField(
    //   onChanged: (value) => setState(() => inputStr = value),
    // );
    return Row(
      children: [
        Text("抽出去一个StatefulWidget组件: $inputStr"),
        SizedBox(width: 20),
        // TextField外层一定要有个Sized组件？ RenderBox was not laid out
        // TextField(),
        Expanded(
          child: TextField(
            onChanged: (value) => setState(() => inputStr = value),
          ),
        ),
      ],
    );
  }
}
